<?php

namespace app\api\controller;

use think\Lang;
	use think\Url;

	/**
 * ============================================================================
 * DSMall多用户商城
 * ============================================================================
 * 版权所有 2014-2028 长沙德尚网络科技有限公司，并保留所有权利。
 * 网站地址: http://www.csdeshang.com
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和使用 .
 * 不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * 控制器
 */
class Sellerjoinin extends MobileMember {

	private $_init_data=[];

	private $joinin_detail=[];
    public function _initialize() {
        
        parent::_initialize();
        Lang::load(APP_PATH . 'home/lang/'.config('default_lang').'/sellerjoinin.lang.php');

        $seller_model = model('seller');
        $seller_info = $seller_model->getSellerInfo(array('member_id' => $this->member_info['member_id']));
        if (!empty($seller_info)) {
	        ds_json_encode(10401,lang('already_sub_account'));
            //$this->success(lang('already_sub_account'),url('Sellerlogin/login'));
            //exit;help_list
        }
        
        if (request()->action() != 'check_seller_name_exist' && request()->action() != 'checkname') {
            $this->check_joinin_state();
        }
        $phone_array = explode(',', config('site_phone'));
        $help_model = model('help');
        $condition = array();
        $condition['helptype_id'] = '99'; //默认显示入驻流程;
	    $help_list = $help_model->h5getShowStoreHelpList($condition);

        $this->_init_data=[
        	'phone_array'=>$phone_array,
        	'help_list'=>array_values($help_list),
        	'show_sign'=>'joinin',
        	'html_title'=>config('site_name') . ' - ' . lang('tenants'),
        	'article_list'=>[]
        ];
    }


    private function check_joinin_state() {
        $storejoinin_model = model('storejoinin');
        $joinin_detail = $storejoinin_model->getOneStorejoinin(array('member_id' => $this->member_info['member_id']));
        if (!empty($joinin_detail)) {
            $this->joinin_detail = $joinin_detail;
	        $this->joinin_detail['store_ids']=unserialize($this->joinin_detail['store_class_ids']);
	        $this->joinin_detail['store_names']=unserialize($this->joinin_detail['store_class_names']);
            switch (intval($joinin_detail['joinin_state'])) {
                case STORE_JOIN_STATE_NEW://申请
                    $this->dostep4();

                    $this->show_join_message(lang('apply_submit_success'), FALSE, '3');
                    break;
                case STORE_JOIN_STATE_PAY://支付
                    $this->show_join_message(lang('pay_submit_success'), FALSE, '4');
                    break;
                case STORE_JOIN_STATE_VERIFY_SUCCESS:
                    if (!in_array(request()->action(), array('pay', 'pay_save'))) {
                        $this->pay();
                    }
                    break;
                case STORE_JOIN_STATE_VERIFY_FAIL:
                    if (!in_array(request()->action(), array('step1', 'step2', 'step3', 'step4'))) {
                        $this->show_join_message(lang('verify_fail').':' . $joinin_detail['joinin_message'],'step1');//跳转
                    }
                    break;
                case STORE_JOIN_STATE_PAY_FAIL:
                    if (!in_array(request()->action(), array('pay', 'pay_save'))) {
                        $this->show_join_message(lang('pay_verify_fail').':' . $joinin_detail['joinin_message'],'pay');//跳转支付
                    }
                    break;
                case STORE_JOIN_STATE_FINAL:
                	ds_json_encode(10010,lang('store_already_open'));//跳转商户登录
                    break;
            }
        }
    }

    public function index() {
        echo $this->step0();exit;
    }

    //协议
    public function step0() {
	    $domain=is_http().$_SERVER['HTTP_HOST'];
	    $url = $domain."/home/member_auth/index.html";
        $document_model = model('document');
        $document_info = $document_model->getOneDocumentByCode('open_store');

        $data=[
        	'agreement'=>htmlspecialchars_decode($document_info['document_content']),
	        'step'=>'0',
	        'sub_step'=>'step0'
        ];
	    ds_json_encode(10000,"查询成功",$this->show_join_data($data));//跳转绑定手机号页面
    }


    public function step1() {
	    $data=[
		    'baidu_ak'=>config('baidu_ak'),
		    'step'=>'1',
		    'sub_step'=>'step1'
	    ];
	    ds_json_encode(10000,"查询成功",$this->show_join_data($data));
    }

    public function step2() {
	    $data=[
		    'step'=>'2',
		    'sub_step'=>'step2'
	    ];
        if (request()->isPost()) {
            $param = array();
            $param['member_name'] = $this->member_info['member_name'];
            $param['company_name'] = input('post.company_name');
            $param['store_longitude']=input('post.longitude');
            $param['store_latitude']=input('post.latitude');
            $param['company_province_id'] = intval(input('post.district_id')?input('post.district_id'):(input('post.city_id')?input('post.city_id'):(input('post.province_id')?input('post.province_id'):0)));
            $param['company_address'] = input('post.company_address');
            $param['company_address_detail'] = input('post.company_address_detail');
            $param['company_registered_capital'] = intval(input('post.company_registered_capital'));
            $param['contacts_name'] = input('post.contacts_name');
            $param['contacts_phone'] = input('post.contacts_phone');
            $param['contacts_email'] = input('post.contacts_email');
            $param['corporate'] = input('post.business_licence_corporate');
	        $param['corporate_idcrad'] = input('post.corporate_idcrad');//法人身份证
	        $param['corporate_phone'] = input('post.corporate_phone');//法人手机号
	        $param['organization_code'] = input('post.organization_code');//组织机构代码
	        $param['tax_register'] = input('post.tax_register');//税务登记证
            $param['business_licence_number'] = input('post.business_licence_number');
            $param['business_licence_address'] = input('post.business_licence_address');
            $param['business_licence_start'] = input('post.business_licence_start');
            $param['business_licence_end'] = input('post.business_licence_end');
            $param['business_sphere'] = input('post.business_sphere');
            $param['business_licence_number_electronic'] = $this->upload_image('business_licence_number_electronic');


            $this->step2_save_valid($param);

            $storejoinin_model = model('storejoinin');
            $joinin_info = $storejoinin_model->getOneStorejoinin(array('member_id' => $this->member_info['member_id']));
            if (empty($joinin_info)) {
                $param['member_id'] = $this->member_info['member_id'];
                $res=$storejoinin_model->addStorejoinin($param);
	            if($res !==false){
		            ds_json_encode(10000,"添加成功");//跳转绑定手机号页面
	            }else{
		            ds_json_encode(10000,"添加失败");//跳转绑定手机号页面
	            }
            } else {
	            $res=$storejoinin_model->editStorejoinin($param, array('member_id' => $this->member_info['member_id']));
	            if($res !==false){
		            ds_json_encode(10000,"更新成功");//跳转绑定手机号页面
	            }else{
		            ds_json_encode(10000,"更新失败");//跳转绑定手机号页面
	            }
            }

        }

	    ds_json_encode(10000,"查询成功",$this->show_join_data($data));

    }

    private function step2_save_valid($param) {
        $sellerjoinin_validate = validate('sellerjoinin');
        if (!$sellerjoinin_validate->scene('step2_save_valid')->check($param)) {
	        ds_json_encode(10001,$sellerjoinin_validate->getError());
        }
    }

    public function step3() {
        if (request()->isPost()) {//提交财务信息
            $param = array();
            $param['bank_account_name'] = input('post.bank_account_name');
            $param['bank_account_number'] = input('post.bank_account_number');
            $param['bank_name'] = input('post.bank_name');
            $param['union_bank'] = input('post.union_bank');
            $param['bank_address'] = input('post.bank_address');
            $is_settlement_account = input('post.is_settlement_account');
            if (!empty($is_settlement_account)) {
                $param['is_settlement_account'] = 1;
                $param['settlement_bank_account_name'] = input('post.bank_account_name');
                $param['settlement_bank_account_number'] = input('post.bank_account_number');
                $param['settlement_bank_name'] = input('post.bank_name');
                $param['settlement_bank_address'] = input('post.bank_address');
                $param['settlement_union_bank'] = input('post.union_bank');
            } else {
                $param['is_settlement_account'] = 2;
                $param['settlement_bank_account_name'] = input('post.settlement_bank_account_name');
                $param['settlement_bank_account_number'] = input('post.settlement_bank_account_number');
                $param['settlement_bank_name'] = input('post.settlement_bank_name');
                $param['settlement_bank_address'] = input('post.settlement_bank_address');
                $param['settlement_union_bank'] = input('post.settlement_union_bank');
            }

            $this->step3_save_valid($param);
            $storejoinin_model = model('storejoinin');
            $res=$storejoinin_model->editStorejoinin($param, array('member_id' => $this->member_info['member_id']));
            if($res !== false){
	            ds_json_encode(10000,"更新成功");
            }else{
	            ds_json_encode(10000,"更新失败");
            }
        }

        //商品分类
        $gc = model('goodsclass');
        $gc_list = $gc->getGoodsclassListByParentId(0);
        $data['gc_list']=$gc_list;
        //$this->assign('gc_list', $gc_list);

        //店铺等级
        $grade_list = rkcache('storegrade', true);
        //附加功能
        if (!empty($grade_list) && is_array($grade_list)) {
            foreach ($grade_list as $key => $grade) {
                $storegrade_function = explode('|', $grade['storegrade_function']);
                if (!empty($storegrade_function[0]) && is_array($storegrade_function)) {
                    $grade_list[$key]['function_str'] = '';
                    foreach ($storegrade_function as $key1 => $value) {
                        if ($value == 'editor_multimedia') {
                            $grade_list[$key]['function_str'] .= lang('rich_text_editor');
                        }
                    }
                } else {
                    $grade_list[$key]['function_str'] = lang('none');
                }
            }
        }
	    $data['grade_list']=array_values($grade_list);
        //$this->assign('grade_list', $grade_list);

        //店铺分类

        $storeclass_model = model('storeclass');
        $store_class = $storeclass_model->getStoreclassList(array(), '', false);
	    $data['store_class']=$store_class;
	    $data['step']='3';
	    $data['sub_step']='step3';

	    ds_json_encode(10000,"查询成功",$this->show_join_data($data));
    }

    private function step3_save_valid($param) {
        $sellerjoinin_validate = validate('sellerjoinin');
        if (!$sellerjoinin_validate->scene('step3_save_valid')->check($param)) {
	        ds_json_encode(10310,$sellerjoinin_validate->getError());
        }
    }

    public function check_seller_name_exist() {
        $condition = array();
        $condition['seller_name'] = input('get.seller_name');

        $seller_model = model('seller');
        $result = $seller_model->isSellerExist($condition);
        if (!$result) {
	        ds_json_encode(10000,"商家账户不存在");
        } else {
	        ds_json_encode(10002,"商家账户已存在");
        }
    }

    //提交店铺信息
    public function step4() {
        $store_class_ids = array();
        $store_class_names = array();

        $store_class_ids_array = input('store_class_ids/a');#获取数组
	    if(empty($store_class_ids_array)){
		    $store_class_ids_array = input('store_class_ids_app');#获取数组
	    }
	    if(!is_array($store_class_ids_array)){
		    $store_class_ids_array=explode(';',$store_class_ids_array);
			//$store_class_ids_array=json_decode($store_class_ids_array,true);
	    }


	    if(!is_array($store_class_ids_array)){
		    ds_json_encode(10001,"数据格式不对");
	    }
	    if (!empty($store_class_ids_array)) {
		    foreach ($store_class_ids_array as $value) {
		    	if(empty($value)){
		    		continue;
			    }
			    $store_class_ids[] = $value;
		    }
	    }
        
        $store_class_names_array = input('post.store_class_names/a');#获取数组
	    if(empty($store_class_names_array)){
		    $store_class_names_array = input('store_class_names_app');#获取数组
	    }
	    if(!is_array($store_class_names_array)){
		    $store_class_names_array=explode(';',$store_class_names_array);
		    //$store_class_names_array=json_decode($store_class_names_array,true);
	    }

	    if(!is_array($store_class_names_array)){
		    ds_json_encode(10002,"数据格式不对");
	    }

        if (!empty($store_class_names_array)) {
            foreach ($store_class_names_array as $value) {
                $store_class_names[] = $value;
            }
        }
        //取最小级分类最新分佣比例
        $sc_ids = array();
        foreach ($store_class_ids as $v) {
            $v = explode(',', trim($v, ','));
            if (!empty($v) && is_array($v)) {
                $sc_ids[] = end($v);
            }
        }
        $store_class_commis_rates = array();
        if (!empty($sc_ids)) {
            $goods_class_list = model('goodsclass')->getGoodsclassListByIds($sc_ids);
            if (!empty($goods_class_list) && is_array($goods_class_list)) {
                $sc_ids = array();
                foreach ($goods_class_list as $v) {
                    $store_class_commis_rates[] = $v['commis_rate'];
                }
            }
        }

	    $store_model = model('store');
	    $store_name = input('post.store_name');
	    $store_info = $store_model->getStoreInfo(array('store_name' => $store_name));
	    if (!empty($store_info['store_name']) && $store_info['member_id'] != $this->member_info['member_id']) {
		    ds_json_encode(10003,"店铺名称已存在");//检查店铺名称是否存在
	    }

        $param = array();
        $param['seller_name'] = input('post.seller_name');
        $param['store_name'] = input('post.store_name');
        $param['store_type'] = 0;
        $param['store_class_ids'] = serialize($store_class_ids);
        $param['store_class_names'] = serialize($store_class_names);
        $param['joinin_year'] = intval(input('post.joinin_year'));
        $param['is_city'] = intval(input('post.is_city',0));//是否同城
        $param['joinin_state'] = STORE_JOIN_STATE_NEW;
        $param['store_class_commis_rates'] = implode(',', $store_class_commis_rates);
        
        //取店铺等级信息
        $grade_list = rkcache('storegrade', true);
        $storegrade_id = intval(input('post.storegrade_id'));
        if($storegrade_id<=0){
            ds_json_encode(10001,lang('param_error'));
        }
        if (!empty($grade_list[$storegrade_id])) {
            $param['storegrade_id'] = $storegrade_id;
            $param['storegrade_name'] = $grade_list[$storegrade_id]['storegrade_name'];
            $param['sg_info'] = serialize(array('storegrade_price' => $grade_list[$storegrade_id]['storegrade_price']));
        }

        //取最新店铺分类信息
        $store_class_info = model('storeclass')->getStoreclassInfo(array('storeclass_id' => intval(input('post.storeclass_id'))));
        if ($store_class_info) {
            $param['storeclass_id'] = $store_class_info['storeclass_id'];
            $param['storeclass_name'] = $store_class_info['storeclass_name'];
            $param['storeclass_bail'] = $store_class_info['storeclass_bail'];
        }

        //店铺应付款
        $param['paying_amount'] = floatval($grade_list[$storegrade_id]['storegrade_price']) * $param['joinin_year'] + floatval($param['storeclass_bail']);
        $this->step4_save_valid($param);

        $storejoinin_model = model('storejoinin');
        $res=$storejoinin_model->editStorejoinin($param, array('member_id' => $this->member_info['member_id']));
        if($res !== false){
	        ds_json_encode(10000,"编辑成功");
        }else{
	        ds_json_encode(10001,"编辑失败");
        }

    }



	//绑定手机号
	public function phone_save() {
		$param = array();

		$phone = input('post.phone');
		$code = input('post.code');
		//$member_validate = validate('member');

		if(!$phone){
			ds_json_encode(10001,"手机号不能为空");
		}
		if(!$code){
			ds_json_encode(10001,"验证码不能为空");
		}

		$tongshang=new Tongshangyun();



		$store_model = model('store');
		$store_info=$store_model->where(['member_id'=>$this->member_info['member_id']])->order('store_id desc')->find();
		if(!$store_info){//$store_info['store_id']
			ds_json_encode(10001,"该店铺不存在");
		}

		$res=$tongshang->bindPhone($store_info['store_id'],$phone,$code,1);
		if(!$res['state']){
			if($res['message'] != "手机已绑定"){
				ds_json_encode(10001,$res['message']);
			}
		}


		$param['joinin_state'] = STORE_JOIN_STATE_PHONE_SUCCESS;
		$storejoinin_model = model('storejoinin');
		$store_res=$storejoinin_model->editStorejoinin($param, array('member_id' => $this->member_info['member_id']));
		if($store_res !== false){
			ds_json_encode(10000,"绑定成功");
		}else{
			ds_json_encode(10000,"绑定失败,请稍后绑定");
		}
	}


	//
	////签约合同
	//public function sign() {
	//	$this->assign('joinin_detail', $this->joinin_detail);
	//	$this->assign('step', '5');
	//	$this->assign('sub_step', 'sign');
	//	echo $this->fetch($this->template_dir . 'sign');
	//	exit;
	//}


	public function sign_save() {

		$tongshang=new Tongshangyun();

		$jumpUrl =input('url',$this->request->domain()."/api/sellerjoinin/pay");
		$store_model = model('store');
		$store_info=$store_model->where(['member_id'=>$this->member_info['member_id']])->order('store_id desc')->find();
		if(!$store_info){
			ds_json_encode(10001,"该店铺不存在");
		}
		//获取用户信息
		$info = $tongshang->getMemberInfo($store_info['store_id'],1);
		if($info['state']){
			if(isset($info['memberInfo']['status']) && $info['memberInfo']['status'] == 2 && $info['memberInfo']['isSignContract']){
				ds_json_encode(10301,"已签约");
			}
		}
		else{
			ds_json_encode(10001,"该企业会员不存在");
		}


		$data=$tongshang->signContract($store_info['store_id'],$jumpUrl,1);
		$data=json_decode($data,true);
		$url="http://116.228.64.55:6900/yungateway/member/signContract.html";//测试
		//$url=" https://fintech.allinpay.com/yungateway/member/signContract.html";//正式
		$sb='';
		foreach ($data as $entry_key => $entry_value) {

			$sb .= $entry_key . '=' . urlencode($entry_value) . '&';

		}
		$site=$url.'?'.$sb;
		ds_json_encode(10000,'查询成功',array('url'=>$site));
	}

    private function step4_save_valid($param) {
        $sellerjoinin_validate = validate('sellerjoinin');
        if (!$sellerjoinin_validate->scene('step4_save_valid')->check($param)) {
	        ds_json_encode(10310,$sellerjoinin_validate->getError());
        }
    }

    public function pay() {
        if (!empty($this->joinin_detail['sg_info'])) {
            $store_grade_info = model('storegrade')->getOneStoregrade($this->joinin_detail['storegrade_id']);
            $this->joinin_detail['storegrade_price'] = $store_grade_info['storegrade_price'];
        } else {
            $this->joinin_detail['sg_info'] = @unserialize($this->joinin_detail['sg_info']);
            if (is_array($this->joinin_detail['sg_info'])) {
                $this->joinin_detail['storegrade_price'] = $this->joinin_detail['sg_info']['storegrade_price'];
            }
        }

	    $data=[
		    'joinin_detail'=>$this->joinin_detail,
		    'joinin_message'=>"审核成功",
		    'btn_next'=>"",
		    'step'=>4,
		    'sub_step'=>'pay',
	    ];
        ds_json_encode(10000,"查询成功",$this->show_join_data($data));
    }

    public function pay_save() {
        $param = array();
        $param['paying_money_certificate'] = $this->upload_image('paying_money_certificate');
        $param['paying_money_certificate_explain'] = input('post.paying_money_certificate_explain');
        $param['joinin_state'] = STORE_JOIN_STATE_PAY;
        if (empty($param['paying_money_certificate'])) {
	        ds_json_encode(10001,lang('paying_money_certificate_empty'));//跳转绑定手机号页面
        }
        $storejoinin_model = model('storejoinin');
	    $res = $storejoinin_model->editStorejoinin($param, array('member_id' => $this->member_info['member_id']));
	    if($res !== false){
		    ds_json_encode(10000,"编辑成功");//跳转绑定手机号页面
	    }else{
		    ds_json_encode(10001,"编辑失败");//跳转绑定手机号页面
	    }
    }


    private function dostep4() {
        if (!empty($this->joinin_detail['sg_info'])) {
            $store_grade_info = model('storegrade')->getOneStoregrade($this->joinin_detail['storegrade_id']);
            $this->joinin_detail['storegrade_price'] = $store_grade_info['storegrade_price'];
        } else {
            $this->joinin_detail['sg_info'] = @unserialize($this->joinin_detail['sg_info']);
            if (is_array($this->joinin_detail['sg_info'])) {
                $this->joinin_detail['storegrade_price'] = $this->joinin_detail['sg_info']['storegrade_price'];
            }
        }

        return $this->joinin_detail;
    }

    private function show_join_message($message, $btn_next = FALSE, $step = '2') {
    	$data=[
    		'joinin_detail'=>$this->joinin_detail,
    		'joinin_message'=>$message,
    		'btn_next'=>$btn_next,
    		'step'=>$step,
    		'sub_step'=>'step4',
	    ];

        ds_json_encode(10000,$message,$this->show_join_data($data));
    }

    private function upload_image($file) {
        //上传文件保存路径
        $pic_name = '';
        $upload_file = BASE_UPLOAD_PATH .DS. 'home'.DS.'store_joinin'.DS;
        if (!empty($_FILES[$file]['name'])) {
            $file_object = request()->file($file);
            //设置特殊图片名称
            $file_name = $this->member_info['member_id'] . '_' . date('YmdHis') . rand(10000, 99999);
            $info = $file_object->rule('uniqid')->validate(['ext' => ALLOW_IMG_EXT])->move($upload_file, $file_name);
            if ($info) {
                $pic_name = $info->getFilename();
            } else {
	            ds_json_encode(10003,$file_object->getError());//跳转绑定手机号页面
                // 上传失败获取错误信息
            }
        }
        return $pic_name;
    }

    /**
     * 检查店铺名称是否存在
     *
     * @param
     * @return
     */
    public function checkname() {
        /**
         * 实例化卖家模型
         */
        $store_model = model('store');
        $store_name = input('get.store_name');
        $store_info = $store_model->getStoreInfo(array('store_name' => $store_name));
        if (!empty($store_info['store_name']) && $store_info['member_id'] != $this->member_info['member_id']) {
	        ds_json_encode(10003,"已存在");//检查店铺名称是否存在
        } else {
	        ds_json_encode(10000,"不存在");//检查店铺名称是否存在
        }
    }

	/**
	 * 合并消息
	 * @param array $data_res
	 */
	private function show_join_data($data_res=[]) {

		$data=[];
		if(!is_array($this->_init_data)){
			$this->_init_data=[];
		}

		if(!is_array($data_res)){
			$data_res=[];
		}
		$data=array_merge($this->_init_data,$data_res);
		return $data;
	}


}

?>
